package com.sbs.demo.utils;

import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;

// https://stackoverflow.com/questions/23732089/how-to-enable-request-scope-in-async-task-executor

/**
 * 线程上下文拷贝装饰器模式
 *
 * @author luwenmin
 * @date 2020/11/13
 */
public class ContextCopyingDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String, String> context = MDC.getCopyOfContextMap();
        return () -> {
            try {
                if (context != null) {
                    MDC.setContextMap(context);
                }
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
